package example.springboot.config;

import example.springboot.model.t_user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private example.springboot.mapper.userMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length != 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    String token = cookie.getValue();
                    t_user t_user = userMapper.byTokenFind(token);
                    if (t_user != null) {
                        request.getSession().setAttribute("t_user",t_user);
                        return true;
                    }
                    break;
                }
            }
        }
        request.getRequestDispatcher("/").forward(request,response);
        return false;
    }
}
